const log4js = require('../../../../utils/logUtils');
const logger = log4js.getLogger('sip');
const zlMediaApi = require("../../../../service/ZlMediaKitApi");
const sip = require("sip");
const deviceCache = require("../../../../db/deviceCache");
const xmlUtils = require("./xmlUtils");
const osUtils = require("../../../../utils/osUtils");
const util = require("../../../../utils/stringUtils");

const TAG = "[ACK响应处理]";
module.exports = {
    async handle(rq) {

        const callid = rq.headers['call-id'];
        const obj = util.sipContent2Object(rq.content);
        // 取 s指令
        logger.info(TAG,'[call-id]=', callid, 'sip invite', obj);

        let {pushKey, stream} = xmlUtils.toLocalPushKey(rq.headers, callid);

        const target = deviceCache.pushArray[pushKey];

        if (!target) {
            logger.info(TAG, "没找到invite缓存信息", deviceCache.pushArray, 'pushKey=', pushKey);
        } else {
            logger.info(TAG, "没找到invite缓存信息", target, 'pushKey=', pushKey);
            let pullUrl, app;
            if (target.s === 'Playback') {
                // tArray是空格分的两个时间戳，改成moment格式
                const startTime = target.startTime;
                const endTime = target.endTime;

                logger.info(TAG, '回放时间', startTime.format('YYYY-MM-DD HH:mm:ss'), '到', endTime.format('YYYY-MM-DD HH:mm:ss'));
                // 找到文件
                const {physicPath, relativePath} = xmlUtils.findFileByTime(startTime, endTime, pushKey);
                if (!physicPath) {
                    logger.error(TAG, '没有找到回放文件', physicPath);
                } else {
                    logger.info(TAG, "查找到回放文件:", physicPath);
                }
                stream = `proxy/${stream}/${startTime.format("YYYY-MM-DD")}/${relativePath}`;
                // 生成点播url，然后添加拉流代理，然后推rtp
                // stream = 'proxy/34010300002000002250_41010500002000000001/2024-01-27/20240127-033436_20240127-035436_1201_203849926.mp4';
                // '/mnt/record1/mp4/record/' + stream
                // const physicPath = config.record.path + '/mp4/record/' + stream;
                await zlMediaApi.pullZlkFfmpeg('record', stream, physicPath);
                await osUtils.sleep(500);
                app = 'record';
                await zlMediaApi.push(app, stream, target.targetIp, target.targetPort, target.localUdpPort, () => {
                    sip.send(sip.makeResponse(rq, 101, 'Dialog Establishement'));
                }, (key) => {
                    if (!deviceCache.pushArray[stream]) {
                        deviceCache.pushArray[stream] = {
                            playing: false,
                            lasttime: new Date()
                        };
                    }
                    if (key) {
                        // 拉流的key
                        deviceCache.pushArray[stream].key = key;
                        deviceCache.pushArray[stream].playing = true;
                    } else {
                        logger.info('播放不成功, stream = ', stream);
                        deviceCache.pushArray[stream].playing = false;
                    }
                    deviceCache.pushArray[stream].lasttime = new Date();
                });
            } else {
                app = 'proxy';
                pullUrl = target.rtsp_url;
                await zlMediaApi.play(app, stream, pullUrl, target.targetIp, target.targetPort, target.localUdpPort, () => {
                    sip.send(sip.makeResponse(rq, 101, 'Dialog Establishement'));
                }, (key) => {
                    if (!deviceCache.pushArray[stream]) {
                        deviceCache.pushArray[stream] = {
                            playing: false,
                            lasttime: new Date()
                        };
                    }
                    if (key) {
                        // 拉流的key
                        deviceCache.pushArray[stream].key = key;
                        deviceCache.pushArray[stream].playing = true;
                    } else {
                        logger.info('播放不成功, stream = ', stream);
                        deviceCache.pushArray[stream].playing = false;
                    }
                    deviceCache.pushArray[stream].lasttime = new Date();
                });
            }
        }
    }
}
